package com.bms.common.base.common.component;

import java.io.InputStream;
import java.net.URL;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.bms.common.base.common.exception.BusinessException;
import com.bms.common.base.common.exception.EnumSvrResult;
import com.bms.common.base.common.util.MD5Util;
import com.feilong.core.Alphabet;
import com.feilong.core.Validator;
import com.feilong.core.date.DateUtil;
import com.feilong.core.util.RandomUtil;

@Component
@PropertySource({ "classpath:oss.properties" })
public class OSSUtil {
	private static Logger log = LoggerFactory.getLogger(OSSUtil.class);

	@Value("${bucketName}")
	private String bucketName;

	@Value("${endpoint}")
	private String endpoint;

	@Value("${accessKeyId}")
	private String accessKeyId;

	@Value("${accessKeySecret}")
	private String accessKeySecret;

	@Value("${ossUrl}")
	private String ossUrl;
	
	private OSSClient client = null;
	
	private void init(){
		client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
	}

	/**
	 * 上传图片到云服务器
	 * 
	 */
	public String saveImage(String prefix, String suffix, Long userId, MultipartFile file) {
		String path = getPath(prefix, suffix, userId);
		try {
			this.init();
			client.putObject(bucketName, path, file.getInputStream());
		} catch (Exception e) {
			log.error("ossUrl:{}", e);
			throw new BusinessException(EnumSvrResult.FILE_UPLOAD_FAIL);
		} finally {
			client.shutdown();
		}
		return ossUrl + "/" + path;
	}

	public String upload(InputStream inputStream, String path) {
		try {
			this.init();
			client.putObject(bucketName, path, inputStream);
		} catch (Exception e) {
			log.error("ossUrl:{}", e);
			throw new BusinessException(EnumSvrResult.FILE_UPLOAD_FAIL);
		} finally {
			client.shutdown();
		}

		return ossUrl + "/" + path;
	}

	public String getOssUrl(String ossPathUrl, String fileName) {
		return new StringBuffer().append(ossPathUrl).append("/").append(fileName).toString();
	}

	public String getPath(String prefix, String suffix, Long userId) {
		String path = "";
		if (Validator.isNotNullOrEmpty(userId)) {
			path = path + "upload/" + userId + "/"+prefix+"/" + DateUtil.toString(new Date(), "yyyy-MM-dd") + "/" + newDateTimeString();
		} else {
			path = path + "upload/default" + "/"+prefix +"/"+ DateUtil.toString(new Date(), "yyyy-MM-dd") + "/" + newDateTimeString();
		}
		return path + suffix;
	}
	
	public InputStream downLoad(URL url){
		try {
			this.init();
			OSSObject obj = client.getObject(new GetObjectRequest(url, null));
			return obj.getObjectContent();
		} catch (Exception e) {
			log.error("下载失败:{}",e.getMessage());
			throw new BusinessException(EnumSvrResult.FILE_UPLOAD_FAIL);
		} finally {
			client.shutdown();
		}
	}

	private static String newDateTimeString() {
		try {
			Thread.sleep(1);
		} catch (InterruptedException e) {
			log.error(e.getMessage());
			Thread.currentThread().interrupt();
		}
		return MD5Util.md5(RandomUtil.createRandomFromString(Alphabet.LOWERCASE , 32)+DateUtil.getTime(new Date()));
	}
}
